from google.appengine.ext import bulkload
from google.appengine.api import datastore_types
from google.appengine.ext import search

from pyth.inventionmodels import *
import os

class CodeLoader(bulkload.Loader):
  def __init__(self):
    # Our 'Person' entity contains a name string and an email
    #print 'here'
    bulkload.Loader.__init__(self, 'CodeSample', 
                         [('name', str),
                            ('lbcodefile' , str),
                            ('pbcodefile' , str),
                            ('textfile' , str),
                            ('lbimage' , str),
                            ('pbimage' , str),
                            ('desc' , lambda x: datastore_types.Text(x.replace('\x0b', ' ').replace('\x1d', ' '))),
                            ('id1' , int),
                            ('author', str),
                            ('creationdate', str),
                          ])

  def HandleEntity(self, entity):
    code = CodeSample()
    code.name = entity['name']
    code.lbcodefile = entity['lbcodefile']
    code.lbimage = entity['lbimage']
    code.pbcodefile = entity['pbcodefile']
    code.pbimage = entity['pbimage']
    code.textfile = entity['textfile']
    code.name = entity['name']
    code.desc = entity['desc']
    code.id1 = entity['id1']
    code.author = entity['author']
    code.creationdate = entity['creationdate']
    
    exists = CodeSample.gql("WHERE name = :1", code.name)
    if exists.count() == 0 or (exists.count() == 1 and exists[0].datetime < code.datetime):
        code.put()
        workshops = Workshop.gql("WHERE codeId = '" + "cd%03d"%(int(entity['id1'])) + "'")
        for w in workshops:
            RelationalEntry(codesample = code, workshop = w).put()

    return None

if __name__ == '__main__':
  bulkload.main(CodeLoader())